﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using yafc.Data;

namespace yafc.UI.Components
{
	public partial class PoolPictureBox : PictureBox
	{
		private string imageLocation;

		public PoolPictureBox()
		{
			LoadCompleted += new AsyncCompletedEventHandler(PoolPictureBox_LoadCompleted);
		}

		// The fucking "help" of PictureBox.ImageLocation.
		// It just load automatically, and it seems impossible to disable it.
		// So I have to add a new variable to hold the imageLocation. DAMN!
		public new string ImageLocation
		{
			get { return imageLocation; }
			set { imageLocation = value; LoadAsync(imageLocation); }
		}

		public new void Load(string Url)
		{
			if (Url == null)
				return;

			imageLocation = Url;
			if (ImagePool.TryGet(Url, OnImageLoad))
				return;

			base.Load(Url);
			OnImageLoad(Url, Image);
		}

		public new void LoadAsync(string Url)
		{
			if (Url == null)
				return;

			imageLocation = Url;
			if (ImagePool.TryGet(Url, OnImageLoad))
				return;

			base.LoadAsync(Url);
		}

		protected void OnImageLoad(string Url, Image image)
		{
			if (image != null)
			{
				this.Image = image;
				ImagePool.Add(Url, image);
				imageLocation = Url;
			}
			else
			{
				Image = ErrorImage;
			}
		}
		private void PoolPictureBox_LoadCompleted(object sender, AsyncCompletedEventArgs e)
		{
			OnImageLoad(imageLocation, Image);
		}
	}
}
